﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Engine.Messaging.Messages;

namespace Engine.Messaging.Listener
{
#if !MESSAGES_OVER_EVENTS
    public class MessageListenersHandle<T> where T : Message
    {
        #region STATIC
        private static MessageListenersHandle<T> _instance;
        public static MessageListenersHandle<T> Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new MessageListenersHandle<T>();
                return _instance;
            }
        }
        #endregion // STATIC


        private List<IMessageListener<T>> Listeners { get; set; }

        private MessageListenersHandle()
        {
            Listeners = new List<IMessageListener<T>>();
        }

        #region Methods
        public void Raise(object sender, T message)
        {
            foreach (var l in Listeners)
                l.Recieve(sender, message);
        }

        public void Add(IMessageListener<T> listener) { Listeners.Add(listener); }
        public void Remove(IMessageListener<T> listener) { Listeners.Remove(listener); }
        #endregion // Methods
    }
#else // MESSAGES_OVER_EVENTS

    public class MessageListenersHandle<T> where T : Message
    {
        #region STATIC
        private static MessageListenersHandle<T> _instance;
        public static MessageListenersHandle<T> Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new MessageListenersHandle<T>();
                return _instance;
            }
        }
        #endregion // STATIC



        public event EventHandler<T> EventHandler;

        #region Methods
        public void Raise(object sender, T message)
        {
            if (EventHandler != null)
                EventHandler(sender, message);
        }

        public void Add(IMessageListener<T> listener) { EventHandler += new EventHandler<T>(listener.Recieve); }
        public void Remove(IMessageListener<T> listener) { EventHandler -= new EventHandler<T>(listener.Recieve); }
        #endregion // Methods
    }
#endif
}
